#include "projectsview.h"
#include "ui_projectsview.h"
#include <QFileDialog>
#include <QSettings>

ProjectsView::ProjectsView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ProjectsView)
{
    ui->setupUi(this);

    connect(ui->newFolder,         SIGNAL(textChanged(QString)), this, SLOT(CheckCanCreate()));
    connect(ui->newName,           SIGNAL(textChanged(QString)), this, SLOT(CheckCanCreate()));
    connect(ui->newPickFolder,     SIGNAL(clicked()),            this, SLOT(SelectFolder()));
    connect(ui->newCreate,         SIGNAL(clicked()),            this, SLOT(TriggerCreateWorld()));
    connect(ui->loadFromFile,      SIGNAL(clicked()),            this, SLOT(LoadFromFile()));
    connect(ui->loadRecentProject, SIGNAL(clicked()),            this, SLOT(LoadRecent()));
    connect(this,                  SIGNAL(LoadProject(QString)), this, SLOT(AddToRecent(QString)));

    QSettings settings;
    int       nRecents = settings.beginReadArray("RecentProjects");

    for (int i = 0 ; i < nRecents ; ++i)
    {
        QString toPrint;

        settings.setArrayIndex(i);
        toPrint = settings.value("path").toString();
        ui->listRecentProjects->addItem(toPrint);
    }
    settings.endArray();
}

void ProjectsView::AddToRecent(QString path)
{
    QSettings   settings;
    QStringList recents;
    int       nRecents = settings.beginReadArray("RecentProjects");

    recents << path;
    for (int i = 0 ; i < nRecents ; ++i)
    {
        QString recent;

        settings.setArrayIndex(i);
        recent = settings.value("path").toString();
        if (path != recent)
          recents << recent;
    }
    settings.endArray();
    settings.remove("RecentProjects");
    settings.beginWriteArray("RecentProjects");
    for (int i = 0 ; i < recents.size() && i < 10 ; ++i)
    {
        settings.setArrayIndex(i);
        settings.setValue("path", recents.at(i));
    }
    settings.endArray();
}

ProjectsView::~ProjectsView()
{
    delete ui;
}

void ProjectsView::SelectFolder()
{
    const QString folderpath = QFileDialog::getExistingDirectory(this, "Dossier du projet");

    ui->newFolder->setText(folderpath);
}

void ProjectsView::CheckCanCreate()
{
    ui->newCreate->setEnabled((ui->newFolder->text().length() > 0 &&
                               ui->newName->text().length() > 0));
}

void ProjectsView::TriggerCreateWorld()
{
    CreateNewProject(ui->newName->text(), ui->newFolder->text());
    AddToRecent(ui->newFolder->text() + PATH_SLASH + ui->newName->text() + ".yml");
}

void ProjectsView::LoadFromFile()
{
    const QString filepath = QFileDialog::getOpenFileName(this, "Fichier de projet");

    if (filepath != "")
      LoadProject(filepath);
}

void ProjectsView::LoadRecent()
{
    if (ui->listRecentProjects->currentItem())
    {
        const QString filepath = ui->listRecentProjects->currentItem()->text();

        LoadProject(filepath);
    }
}
